//
//  MPPlatformFilterTableController.m
//  M800Project
//
//  Created by 姚宗超 on 14/11/7.
//  Copyright (c) 2014年 姚宗超. All rights reserved.
//

#import "MPPlatformFilterTableController.h"
#import "MPNetworkService.h"
#import "MPFilterConditionCell.h"
#import "MPFilterResultCell.h"
#import "MPDeviceObject.h"
#import "MPFilterConditionItem.h"
#import "MPFilterResultItem.h"
#import "MPCellButton.h"
#import "MPPlatformFilterSectionView.h"
#import "MPAddPlatformTableController.h"
#import "NSDictionary+Common.h"
#import "MPSwitchTableCell.h"
#import "MPCellSwitch.h"

@interface MPPlatformFilterTableController ()
@property (nonatomic, strong)MPPlatformFilterSectionView* firstSectionView;
@property (nonatomic, strong)MPPlatformFilterSectionView* secondSectionView;
@property (nonatomic, strong)KDTableViewSectionObject* fourSecionObject;

@end

@implementation MPPlatformFilterTableController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.title = @"筛选设置";
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButton.frame = CGRectMake(0, 0, 25, 25);
    [leftButton setBackgroundImage:[UIImage imageForKey:@"nav_back_icon"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backNavItemPressed) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.hidesBackButton = YES;
}

- (void)backNavItemPressed
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self createModel];
}

- (KDTableViewSectionObject *)fourSecionObject
{
    if (!_fourSecionObject) {
        _fourSecionObject = [[KDTableViewSectionObject alloc] init];
    }
    return _fourSecionObject;
}

- (void)createModel
{
    @weakify(self);
    [MPNetworkService fetchMySubcribeInfoWithDeviceId:[MPDeviceObject sharedInstance].deviceId onCompletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
        @normalize(self);
        if (errorMsg) {
            [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
            return ;
        }
        
        [self.firstSectionObject.items removeAllObjects];
        [self.secondSectionObject.items removeAllObjects];
        [self.thirdSectionObject.items removeAllObjects];
        [self.fourSecionObject.items removeAllObjects];
        [self.sections removeAllObjects];
        
        // section 1
        [MPDeviceObject sharedInstance].isPushOn = [info boolValueForKey:@"openAPPPushSwitch"];
        [self.firstSectionObject.items addObject:[MPDeviceObject sharedInstance]];
        [self.sections addObject:self.firstSectionObject];
        
        // section 2
        [[MPDeviceObject sharedInstance].platformNameArray removeAllObjects];
        NSArray* platformArray = [info objectForKey:@"platform"];
        __block NSMutableString* platformString = [NSMutableString string];
        [platformArray enumerateObjectsUsingBlock:^(NSDictionary* platformInfoDic, NSUInteger idx, BOOL *stop) {
            if (idx < platformArray.count - 1) {
                [platformString appendFormat:@"%@    ", [platformInfoDic objectForKey:@"platformName"]];
            }
            else if (idx == platformArray.count - 1)
            {
                [platformString appendFormat:@"%@", [platformInfoDic objectForKey:@"platformName"]];
            }
            // TODO codeId数组存储
            [[MPDeviceObject sharedInstance].platformNameArray addObject:[platformInfoDic objectForKey:@"platformName"]];
        }];
        MPFilterResultItem* item = [MPFilterResultItem itemWithTitle:@"已选择平台" content:platformString];
        [self.secondSectionObject.items addObject:item];
        [self.sections addObject:self.secondSectionObject];

        // section 3
        [[MPDeviceObject sharedInstance].durationCodeArray removeAllObjects];
        NSArray* durationCodeArray = [self p_durationCodeArrayFromJsonArray:[info objectForKey:@"repayLimitTime"]];
        [[MPDeviceObject sharedInstance].durationCodeArray addObjectsFromArray:durationCodeArray];
        [[MPDeviceObject sharedInstance].durationNameArray removeAllObjects];
        
        NSString *durationPlistPath = [[NSBundle mainBundle] pathForResource:@"bid_duration" ofType:@"plist"];
        NSArray *durationArray=[[NSArray  alloc] initWithContentsOfFile:durationPlistPath];
        [durationArray enumerateObjectsUsingBlock:^(NSDictionary* durationInfoDic, NSUInteger idx, BOOL *stop) {
            if (idx > 0 && idx < durationArray.count) {
                MPFilterConditionItem* durationItem = [MPFilterConditionItem itemWithPlistInfoDic:durationInfoDic];
                if ([durationCodeArray containsObject:durationItem.code]) {
                    if (![[MPDeviceObject sharedInstance].durationNameArray containsObject:durationItem.title]) {
                        [[MPDeviceObject sharedInstance].durationNameArray addObject:durationItem.title];
                    }
                    durationItem.isSelected = YES;
                }
                else
                {
                    durationItem.isSelected = NO;
                }
                
                [self.thirdSectionObject.items addObject:durationItem];
            }
        }];
        [self.sections addObject:self.thirdSectionObject];
        
        // section 4
        [[MPDeviceObject sharedInstance].yearRateCodeArray removeAllObjects];
        NSArray* yearRateCodeArray = [self p_yearRateCodeArrayFromJsonArray:[info objectForKey:@"yearRate"]];
        [[MPDeviceObject sharedInstance].yearRateCodeArray addObjectsFromArray:yearRateCodeArray];
        
        [[MPDeviceObject sharedInstance].yearRateNameArray removeAllObjects];
        
        NSString *yearRatePlistPath = [[NSBundle mainBundle] pathForResource:@"bid_year_rate" ofType:@"plist"];
        NSArray *yearRateArray=[[NSArray  alloc] initWithContentsOfFile:yearRatePlistPath];
        [yearRateArray enumerateObjectsUsingBlock:^(NSDictionary* yearRateInfoDic, NSUInteger idx, BOOL *stop) {
            if (idx > 0 && idx < yearRateArray.count) {
                MPFilterConditionItem* yearRateItem = [MPFilterConditionItem itemWithPlistInfoDic:yearRateInfoDic];
                if ([yearRateCodeArray containsObject:yearRateItem.code]) {
                    if (![[MPDeviceObject sharedInstance].yearRateNameArray containsObject:yearRateItem.title]) {
                        [[MPDeviceObject sharedInstance].yearRateNameArray addObject:yearRateItem.title];
                    }
                    yearRateItem.isSelected = YES;
                }
                else
                {
                    yearRateItem.isSelected = NO;
                }
                [self.fourSecionObject.items addObject:yearRateItem];
            }
        }];
        [self.sections addObject:self.fourSecionObject];
        
        if ([MPDeviceObject sharedInstance].durationNameArray.count > 0) {
            self.firstSectionView.contentLabel.text = [[MPDeviceObject sharedInstance].durationNameArray componentsJoinedByString:@","];
        }
        else
        {
            self.firstSectionView.contentLabel.text = @"暂未选择";
        }
        
        if ([MPDeviceObject sharedInstance].yearRateNameArray.count > 0) {
            self.secondSectionView.contentLabel.text = [[MPDeviceObject sharedInstance].yearRateNameArray componentsJoinedByString:@","];
        }
        else
        {
            self.secondSectionView.contentLabel.text = @"暂未选择";
        }
        
        [self.tableView reloadData];
    }];
}

- (NSArray *)p_durationCodeArrayFromJsonArray:(NSArray *)jArray
{
    NSMutableArray* resultArray = [NSMutableArray array];
    for (NSDictionary* infoDic in jArray) {
        [resultArray addObject:[infoDic objectForKey:@"repayLimitTimeCode"]];
    }
    return resultArray;
}

- (NSArray *)p_yearRateCodeArrayFromJsonArray:(NSArray *)jArray
{
    NSMutableArray* resultArray = [NSMutableArray array];
    for (NSDictionary* infoDic in jArray) {
        [resultArray addObject:[infoDic objectForKey:@"yearRateCode"]];
    }
    return resultArray;
}

#pragma mark - property
- (MPPlatformFilterSectionView *)firstSectionView
{
    if (!_firstSectionView) {
        _firstSectionView = [[MPPlatformFilterSectionView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 44.0f)];
        _firstSectionView.titleLabel.text = @"年化收益";
    }
    return _firstSectionView;
}

- (MPPlatformFilterSectionView *)secondSectionView
{
    if (!_secondSectionView) {
        _secondSectionView = [[MPPlatformFilterSectionView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 44.0f)];
        _secondSectionView.titleLabel.text = @"投资期限";
    }
    return _secondSectionView;
}


#pragma mark - protocol
// 注册cell的类型，子类实现
- (void)registerCellClass
{
    NSArray* cellClassArray = [NSArray arrayWithObjects:[MPFilterConditionCell class], [MPFilterResultCell class], [MPSwitchTableCell class], nil];
    for (Class cls in cellClassArray) {
        NSString* path = [[NSBundle mainBundle] pathForResource:[cls className] ofType:@"nib"];
        if ([NSString stringIsEmpty:path]) {
            [self.tableView registerClass:cls forCellReuseIdentifier:[cls className]];
        }
        else
        {
            UINib* nib = [UINib nibWithNibName:[cls className] bundle:nil];
            [self.tableView registerNib:nib forCellReuseIdentifier:[cls className]];
        }
    }
}

// 从object获取cell的类名
- (Class)cellClassByObject:(id)object
{
    if ([object isKindOfClass:[MPFilterResultItem class]]) {
        return [MPFilterResultCell class];
    }
    else if ([object isKindOfClass:[MPFilterConditionItem class]])
    {
        return [MPFilterConditionCell class];
    }
    else if ([object isKindOfClass:[MPDeviceObject class]])
    {
        return [MPSwitchTableCell class];
    }
    return nil;
}

- (void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        // 跳转选择平台
        MPAddPlatformTableController* vc = [[MPAddPlatformTableController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.section == 2)
    {
        MPFilterConditionItem* item = [self objectAtIndexPath:indexPath];
        if (item.isSelected) {
            if ([[MPDeviceObject sharedInstance].durationCodeArray containsObject:item.code]) {
                [[MPDeviceObject sharedInstance].durationCodeArray removeObject:item.code];
            }
            if ([[MPDeviceObject sharedInstance].durationNameArray containsObject:item.title]) {
                [[MPDeviceObject sharedInstance].durationNameArray removeObject:item.title];
            }
        }
        else
        {
            if (![[MPDeviceObject sharedInstance].durationCodeArray containsObject:item.code]) {
                [[MPDeviceObject sharedInstance].durationCodeArray addObject:item.code];
            }
            if (![[MPDeviceObject sharedInstance].durationNameArray containsObject:item.title]) {
                [[MPDeviceObject sharedInstance].durationNameArray addObject:item.title];
            }
        }
        [MPNetworkService modifyMySubcribeWithDeviceObject:[MPDeviceObject sharedInstance] onCompletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
            if (errorMsg) {
                [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
                if (item.isSelected) {
                    if (![[MPDeviceObject sharedInstance].durationCodeArray containsObject:item.code]) {
                        [[MPDeviceObject sharedInstance].durationCodeArray addObject:item.code];
                    }
                    if (![[MPDeviceObject sharedInstance].durationNameArray containsObject:item.title]) {
                        [[MPDeviceObject sharedInstance].durationNameArray addObject:item.title];
                    }
                }
                else
                {
                    if ([[MPDeviceObject sharedInstance].durationCodeArray containsObject:item.code]) {
                        [[MPDeviceObject sharedInstance].durationCodeArray removeObject:item.code];
                    }
                    if ([[MPDeviceObject sharedInstance].durationNameArray containsObject:item.title]) {
                        [[MPDeviceObject sharedInstance].durationNameArray removeObject:item.title];
                    }
                }
                return ;
            }
            item.isSelected = !item.isSelected;
            if ([MPDeviceObject sharedInstance].durationNameArray.count > 0) {
                self.firstSectionView.contentLabel.text = [[MPDeviceObject sharedInstance].durationNameArray componentsJoinedByString:@","];
            }
            else
            {
                self.firstSectionView.contentLabel.text = @"暂未选择";
            }
        }];
    }
    else if (indexPath.section == 3)
    {
        MPFilterConditionItem* item = [self objectAtIndexPath:indexPath];
        if (item.isSelected) {
            if ([[MPDeviceObject sharedInstance].yearRateCodeArray containsObject:item.code]) {
                [[MPDeviceObject sharedInstance].yearRateCodeArray removeObject:item.code];
            }
            if ([[MPDeviceObject sharedInstance].yearRateNameArray containsObject:item.title]) {
                [[MPDeviceObject sharedInstance].yearRateNameArray removeObject:item.title];
            }
        }
        else
        {
            if (![[MPDeviceObject sharedInstance].yearRateCodeArray containsObject:item.code]) {
                [[MPDeviceObject sharedInstance].yearRateCodeArray addObject:item.code];
            }
            if (![[MPDeviceObject sharedInstance].yearRateNameArray containsObject:item.title]) {
                [[MPDeviceObject sharedInstance].yearRateNameArray addObject:item.title];
            }
        }

        [MPNetworkService modifyMySubcribeWithDeviceObject:[MPDeviceObject sharedInstance] onCompletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
            if (errorMsg) {
                [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
                if (item.isSelected) {
                    if (![[MPDeviceObject sharedInstance].yearRateCodeArray containsObject:item.code]) {
                        [[MPDeviceObject sharedInstance].yearRateCodeArray addObject:item.code];
                    }
                    if (![[MPDeviceObject sharedInstance].yearRateNameArray containsObject:item.title]) {
                        [[MPDeviceObject sharedInstance].yearRateNameArray addObject:item.title];
                    }
                }
                else
                {
                    if ([[MPDeviceObject sharedInstance].yearRateCodeArray containsObject:item.code]) {
                        [[MPDeviceObject sharedInstance].yearRateCodeArray removeObject:item.code];
                    }
                    if ([[MPDeviceObject sharedInstance].yearRateNameArray containsObject:item.title]) {
                        [[MPDeviceObject sharedInstance].yearRateNameArray removeObject:item.title];
                    }
                }
                return ;
            }
            item.isSelected = !item.isSelected;
            if ([MPDeviceObject sharedInstance].yearRateNameArray.count > 0) {
                self.secondSectionView.contentLabel.text = [[MPDeviceObject sharedInstance].yearRateNameArray componentsJoinedByString:@","];
            }
            else
            {
                self.secondSectionView.contentLabel.text = @"暂未选择";
            }
        }];
    }
}

- (UIView *)viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    if (section == 0) {
        return nil;
    }
    else if (section == 1)
    {
        return self.firstSectionView;
    }
    else if (section == 2)
    {
        return self.secondSectionView;
    }
    else
    {
        return nil;
    }
}

- (UIView *)viewForFooterInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    if (section == 0) {
        return nil;
    }
    else if (section == 1)
    {
        return nil;
    }
    else if (section == 2)
    {
        UIView* footerView = [UIView new];
        UILabel* label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:kDescribeFontSize];
        label.textColor = [UIColor colorWithHexString:kTextUnSelectedGrayColor];
        label.text = @"筛选成功后，你可在 我要抢标 中查看";
        [footerView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(footerView);
            make.top.mas_equalTo(footerView).with.offset(10.0f);
            make.bottom.mas_equalTo(footerView).with.offset(-10.0f);
        }];
        
        return footerView;
    }
    else
    {
        return nil;
    }
}

- (void)setupControlAction:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath
{
    KDLogTrace();
    if (indexPath.section == 0) {
        //
        MPSwitchTableCell* switchCell = (MPSwitchTableCell *)cell;
        switchCell.switchCtrl.indexPath = indexPath;
        [switchCell.switchCtrl addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
        
    }
}

- (void)switchChanged:(id)sender
{
    KDLogTrace();
    MPCellSwitch* switchCtrl = (MPCellSwitch *)sender;
    [MPNetworkService modifyPushStateWithDeviceId:[MPDeviceObject sharedInstance].deviceId state:!switchCtrl.isOn onCompletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
        if (errorMsg) {
            [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
            return ;
        }
        [switchCtrl setOn:!switchCtrl.isOn animated:YES];
    }];
}

@end
